<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>人员管理</title>
    <link rel="stylesheet" type="text/css" href="resources/css/ext-all.css" />
    <script type="text/javascript" src="js/ext-base.js"></script>
    <script type="text/javascript" src="js/ext-all.js"></script>
</head>
<body style="padding:10px;">
<div id="north-div"></div>
<div id="center"></div>
<script type="text/javascript">
Ext.onReady(function(){
	//编码方式
	Ext.lib.Ajax.defaultPostHeader += '; charset=utf-8';
	//使用表单提示
	Ext.QuickTips.init();
	Ext.form.Field.prototype.msgTarget = 'side';
    var ds = new Ext.data.Store({//这是数据源
        proxy : new Ext.data.HttpProxy({url:'staff/list.action'}),
        reader: new Ext.data.JsonReader({
            root: 'topics',
            totalProperty: 'totalCount',
            id: 'id'
            },[{
                   name:'id'
               },{
                   name:'name'
               },{
                   name:'mobile'
               },{
                   name:'department'
               },{
                   name:'professions'
               },{
                   name:'special'
               },{
                   name:'mobileID'
               }])
    });

    var departDS = new Ext.data.Store({//这是数据源
        proxy : new Ext.data.HttpProxy({url:'staff/deprtList.action'}),
        reader: new Ext.data.JsonReader({
            root:'topics',
            totalProperty: 'totalCount',
            id: 'id'
            },[{name:'id'},{name:'name'}])
    });
    
    var persDS = new Ext.data.Store({//这是数据源
        proxy : new Ext.data.HttpProxy({url:'staff/persList.action'}),
        reader: new Ext.data.JsonReader({
            root:'topics',
            totalProperty: 'totalCount',
            id: 'id'
            },[{name:'id'},{name:'name'}])
    });

    var _specials = [['0','高层'],['1','中层'],['2','普通']]
    
    var colModel = new Ext.grid.ColumnModel([//定义列
         {header:'ID',width:50,sortable:true,dataIndex:'id'},
         {id:'title',header:'用户名', width:100,sortable:true,dataIndex:'name'},
         {header:'手机号码',width:100,sortable:true,dataIndex:'mobile'},
         {header:'设备号码',width:150,sortable:true,dataIndex:'mobileID'},
         {header:'所在部门',width:200,sortable:true,dataIndex:'department',renderer:function(data){return data.name;}},
         {header:'工作组',width:200,sortable:true,dataIndex:'professions',renderer:function(data){var dNames = [];for(var i=0;i<data.length;i++){dNames.push(data[i].name)}return dNames.join(',')}},
         {header:'用户级别',width:100,sortable:true,dataIndex:'special',renderer:function(data){return _specials[data][1];}}
        ]);
    var tb = new Ext.Toolbar('north-div');//创建一个工具条
   
    tb.add({
        id:'addstaffBtn',
        text: '添加',
        handler: newUser
        },{
        text: '编辑',
        handler: editUser
        },{
        text: '删除',
        handler: delUser
    });
 
    var grid = new Ext.grid.GridPanel({//列表
                border:false,
                region:'center',
                loadMask: true,
                el:'center',
                title:'条目列表',
                store: ds,
                cm: colModel,
                autoScroll: true,
                bbar: new Ext.PagingToolbar({
                    pageSize: 20,
                    store: ds,
                    displayInfo: true,
                    displayMsg: '第{0} 到 {1} 条数据 共{2}条',
                    emptyMsg: "没有数据"
                })
            });
    
    var top = new Ext.FormPanel({//这里是搜索表单
        buttonAlign:'right',
        labelWidth:70,
        region:'north',
        height:100,
        frame:true,
        title: '搜索',
        items: [{
                layout:'column',
                items:[{
                    columnWidth:.25,
                    layout: 'form',
                    items: [{
                        xtype:'textfield',
                        fieldLabel: '姓名',
                        id: 'sel_staff_name',
                        name: 'staff.name',
                        anchor:'90%'
                    }]
                },{
                    columnWidth:.25,
                    layout: 'form',
                    items: [{
                        xtype:'textfield',
                        fieldLabel: '手机',
                        id: 'sel_staff_mobile',
                        name: 'staff.mobile',
                        anchor:'90%'
                    }]
                },{
                    columnWidth:.25,
                    layout: 'form',
                    items: [{
                        xtype:'textfield',
                        fieldLabel: '部门',
                        name: 'staff.department.name',
                        id: 'sel_staff_depart_name',
                        anchor:'90%'
                    }]
                },{
                    columnWidth:.25,
                    layout: 'form',
                    items: [{
                        xtype:'textfield',
                        fieldLabel: '工作组',
                        name: 'profe.name',
                        id: 'sel_staff_profe_name',
                        anchor:'90%'
                    }]
                }]
            }
        ],

        buttons: [{
            text: '搜索',
            handler:function(){loadList();}
        }]
    });
    
    var viewport = new Ext.Viewport({
        id:'viewport',
        layout:'border',
        items:[{
              border:false,
              region:'north',
              contentEl:'north-div',
              tbar:tb,
              height:26
            },{
                layout:"border",
                region:'center',
                border:false,
                items:[top,grid]
                }
        ]}
    );

    var loadList = function(){
	    ds.load({params:{start:0, limit:20},callback:function(r,options,success){
		    if(!success){//没取到数据时返回的success=false
		        grid.store.removeAll();//清除原有数据
		  }
	    }});
    }
    
    loadList();
        
    // 这里很关键，如果不加，翻页后搜索条件就变没了，这里的意思是每次数据载入前先把搜索表单值加上去，这样就做到了翻页保留搜索条件了
    ds.on('beforeload',function(){
        Ext.apply(
        this.baseParams,
        {
            'staff.name':Ext.get('sel_staff_name').dom.value,
            'staff.mobile':Ext.get('sel_staff_mobile').dom.value,
            'staff.department.name':Ext.get('sel_staff_depart_name').dom.value,
            'profe.name':Ext.get('sel_staff_profe_name').dom.value
        });
    });

    var simple = new Ext.FormPanel({
        labelWidth: 75,
        frame:true,
        bodyStyle:'padding:10px 5px 0px 30px',
        width: 350,
        defaults: {width: 230,enableKeyEvents:true}, 
        defaultType: 'textfield',
        items: [{
                fieldLabel: '用 户 名',
                name: 'staff.name',
                id:'staff_name',
                allowBlank:false
                
            },{
                fieldLabel: '手机号码',
                name: 'staff.mobile',
                id:'staff_mobile',
                listeners : {
					'keyup':function(node,event){
;			              addDialog.buttons[0].setDisabled(false);
			        }
                }
            },{
                fieldLabel: '设备号码',
                name: 'staff.mobileID',
                id:'staff_mobileID'
            },{
            	xtype:'combo',
            	fieldLabel: '所属部门',
                id:'staff_deprt_id',
                store:departDS,
                displayField:'name',
                valueField:'id',
                hiddenName:'staff.department.id',
                typeAhead: true,
                forceSelection: true,
                selectOnFocus:true,
                mode:'remote',
                triggerAction: 'all',
                emptyText:'请指定所属部门...'
            },{
               	xtype:'combo',
                fieldLabel: '具体工作组',
                id:'staff_profe_id',
                store:persDS,
                displayField:'name',
                valueField:'id',
                hiddenName:'persIds',
                typeAhead: true,
                forceSelection: true,
                selectOnFocus:true,
                mode:'remote',
                triggerAction: 'all',
                listeners : {
					'focus':function(node,event){
				          var p = {};
				          p.vas = Ext.getCmp('staff_profe_id').getValue();
				          p.ids = Ext.getCmp('staff_profe_id').hiddenField.value;
			              showSelDialog(p,'pro',function(o){
			            	    Ext.getCmp('staff_profe_id').setValue(o.vas.join(','));
			            	    Ext.getCmp('staff_profe_id').hiddenField.value = o.ids.join(',');
					      });
			        }
                },
                emptyText:'请指定从事工作组...'
            },{
    	        xtype:'combo',
            	hiddenName:'staff.special',
		        id:'staff_special',
    	        fieldLabel: '用户级别',
    	        store:{
        	        xtype:'arraystore',
					fields:['id','val'],
					data:_specials
    	         },
    	        valueField: 'id',
	            displayField:'val',
	            mode: 'local',
	            value:'2',
	            forceSelection:true,
	            typeAhead: true,
	            width:150,
	            triggerAction: 'all'
            },{
                xtype:'hidden',
                id:'staff_id',
                name:'staff.id'
            }]
    });
    
    var doClose = function(){
        addDialog.hide();
    }

    var doAdd = function(){
    	//提交到服务器操作
        simple.form.doAction('submit',{
          url:'staff/add.action',//文件路径
          method:'post',//提交方法post或get
          //提交成功的回调函数
          success:function(response,options){
        	  addDialog.hide();
        	  if(Ext.get('staff_id').dom.value != null&&Ext.get('staff_id').dom.value != ''){
	        	  Ext.get('staff_id').dom.value = '';
	        	  Ext.Msg.alert('编辑成功','  恭喜您成功地修改了人员信息！',function(){ds.reload();});
              }else{
	        	  Ext.Msg.alert('添加成功','  恭喜您成功地添加了新的人员！',function(){ds.reload();});
              }
          },
          //提交失败的回调函数
          failure:function(response,options){
        	  Ext.Msg.alert('错误','请检查您的输入是否为空,如果多次确认无法成功请与系统管理员联系!！');
          }
        });
    }
    
    var addDialog;

    var initEditDialog = function(title){
        if(!addDialog){
        	addDialog = new Ext.Window({
     			layout:'fit',
     			width:400,
     			height:260,
     			closeAction:'hide',
     			plain:true,
     			buttons:[{text:'保存',disabled:true,handler:doAdd},{text:'关闭',handler:doClose}],
     			items:simple
         });
        }
        addDialog.setTitle(title);
    }
    
    function newUser() {
    	initEditDialog('新增人员');
    	try{Ext.get('staff_id').dom.value = '';}catch(e){}
        addDialog.show('addstaffBtn');
    }

    var getSelPros = function(o,name){
        var res = [];
        for(var i=0;i<o.length;i++){
            res.push(o[i][name]);
        }
        return res.join(',');
    }
    
    function editUser() {
        var s = grid.getSelectionModel().getSelections();
        if (s.length>1) {
            Ext.Msg.alert('出错啦','您选择了 '+s.length+' 条记录,目前只支持一次编辑一条记录！');
            return false;
        }
        if (s.length==0) {
            Ext.Msg.alert('出错啦','你还没有选择要操作的记录！');
            return false;
        }
  	    initEditDialog('编辑人员');
  	    addDialog.show('addstaffBtn');
  	    Ext.get('staff_id').dom.value = s[0].data.id;
  	    Ext.get('staff_name').dom.value = s[0].data.name;
  	    Ext.get('staff_mobile').dom.value = s[0].data.mobile;
  	    Ext.get('staff_mobileID').dom.value = s[0].data.mobileID;
  	    Ext.getCmp('staff_deprt_id').setValue(s[0].data.department.name);
  	    Ext.getCmp('staff_deprt_id').hiddenField.value = s[0].data.department.id;
  	    
  	    Ext.getCmp('staff_profe_id').setValue(getSelPros(s[0].data.professions,'name'));
  	    Ext.getCmp('staff_profe_id').hiddenField.value = getSelPros(s[0].data.professions,'id');
  	    
  	    Ext.getCmp('staff_special').setValue(_specials[s[0].data.special][1]);
	    Ext.getCmp('staff_special').hiddenField.value = s[0].data.special;
    }

    var getIds = function(g){
    	var s = g.getSelectionModel().getSelections();
    	 if (s.length==0) {
             return false;
         }
         var ids = [];
         for(var i=0;i<s.length;i++){
             ids.push(s[i].data.id);
         }
         return ids.join(',');
    }

    var delSucc = function(result){
    	loadList();
    }
    
    function delUser() {
        var ids = getIds(grid);
        if (ids) {
            Ext.Msg.confirm('确认', '真的要删除吗？', function(btn){
                if (btn == 'yes'){
                    Ext.Ajax.request({
                       url: 'staff/del.action?staffIds='+ids,
                       success:delSucc
                    });
                }
            });       
        } else {
            Ext.Msg.alert('出错啦','你还没有选择要操作的记录！');
        }
    }

    var getMDialog = function(mData,type,fn,p){
        
        var getMHTML = function(d,sis){
          var ids = {};	
          if(sis&&sis.ids){
              var sids = sis.ids.split(',');
              for(var i=0;i<sids.length;i++){
            	  ids[sids[i]] = true;
              }
          }
          var res = [];
          res.push( '<table style="width:100%;text-align:left;margin-top:10px;"><tr style="border-bottom:1px solid blue"><td colspan="2"><input id="'+type+'_sel"></input></td><td> 全选 &nbsp;&nbsp;<input type="checkbox" id="'+type+'_selAll"></input></td></tr>');
          for(var i=0;i<d.length;i+=4){
                res.push('<tr>');
                for(var j=0;j<4;j++){
                    var index = i+j; 
                    var cstr =  d[index]&&d[index].id&&ids[d[index].id]?' checked = "checked" ':"";
                    var c = d[index]&&d[index].id?'<input type="checkbox" name="'+type+'_xx" value="'+d[index].id+'" dname="'+d[index].name+'" '+cstr+'> '+d[index].name:'';
                    res.push('<td>'+c+'</td>'); 
                }
                res.push('</tr>');
          }
          res.push('</table>');
          return res.join('');
        }        

         var doClose = function(){
             getMDialog[type].hide();
             addDialog.show();
         }

         var doSel = function(){
           getMDialog[type].hide();
           var cs = document.getElementsByName(type+'_xx');
           var o = {};
           o.ids = [];
           o.vas = [];
           for(var i=0;i<cs.length;i++){
               if(cs[i].checked){
                   o.ids.push(cs[i].value);
                   o.vas.push(cs[i].getAttribute('dname'));
               }
           }
           if(fn)fn(o);
           addDialog.show();
         }

         var selAll = function(t){
         	var cs = document.getElementsByName(type+'_xx');
         	for(var i=0;i<cs.length;i++){
                     cs[i].checked = t;
             }
         }
         
         var likeSel = function(v){
         	var cs = document.getElementsByName(type+'_xx');
         	for(var i=0;i<cs.length;i++){
                 if(cs[i].getAttribute('dname').indexOf(v)!=-1){
                     cs[i].checked = true;
                 }else{
                     cs[i].checked = false;
                 }
             }
         }
         
         if(!getMDialog[type]){
              getMDialog[type] = new Ext.Window({
                      layout:'fit',
                      width:500,
                      height:300,
                      closeAction:'hide',
                      modal:true,
                      plain:true,
                      buttons:[{text:'确认',disabled:false,handler:doSel},{text:'关闭',handler:doClose}],
                      html:'<div style="width:100%;height:100%;overflow-y:auto;" id = "'+type+'_dialog_div">'+getMHTML(mData,p)+'</div>' 
               });
         }else{
        	 	document.getElementById(type+'_dialog_div').innerHTML = getMHTML(mData,p);
         }
         getMDialog[type].show();
         document.getElementById(type+'_sel').onkeyup = function(){
         	likeSel(this.value);
         }
         document.getElementById(type+'_selAll').onclick = function(){
         	selAll(this.checked);
         }
     }

     var showSelDialog = function(p,type,fn){
    	 addDialog.hide();
    	 var mk = new Ext.LoadMask(document.body, {
    		 msg: '正在获取数据，请稍候!',
    		 removeMask: true //完成后移除
    	 });
    	 mk.show();
	     Ext.Ajax.request({
	     		url: 'polling/list.action',
	   			params: {
	    	 		tType:type,
	   			},
	     	 	success: function(response, options) {
	   			var mData = Ext.util.JSON.decode(response.responseText);                                             
	     			if(mData&&mData.topics){
		     			mk.hide();
	     			    var dialog = getMDialog(mData.topics,type,fn,p);  
	     			}
	     		},
	            failure:function(response,options){
	     		  mk.hide();
	          	  Ext.Msg.alert('错误','请检查您的输入是否为空,如果多次确认无法成功请与系统管理员联系!！');
	            }
	 	 });
     }
    
});
</script>
</body>
</html>